<template>
  <div class="meter-reading">
    <div class="demo-progress" v-if="percentageFlag">
      <el-progress :stroke-width="10" :percentage="percentage" />
    </div>
    <div>
      <el-table
        ref="dataTabRef"
        v-loading="loadingRef"
        :data="tableData"
        @selection-change="handleSelectionChange"
        @header-click="headerClick"
        @cell-click="cellClick"
        @row-click="rowClick"
        border
        style="width: 100%"
        class="meter-reading-tab"
        :cell-class-name="tableCellClassName"
      >
        <el-table-column fixed prop="label" label="" width="180" />
        <el-table-column fixed type="selection" width="55" align="center">
        </el-table-column>
        <el-table-column
          v-for="(item, key) in tableHeader"
          :key="key"
          :prop="item.position + ''"
          :label="
            (item.pname ? item.pname : '') +
            item.name +
            (item.position ? '[' + item.position + '' + ']' : '')
          "
          align="center"
          width="100"
        >
          <template #default="scope">
            <el-input
              disabled
              v-model="scope.row['value' + item.position]"
            ></el-input>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="ll-control">
      <div class="ll-control-item">
        <el-radio-group v-model="readRadio" class="ll-group">
          <el-radio label="1">选中数据</el-radio>
          <el-radio label="2">当前表数据</el-radio>
          <el-radio label="3">所有表数据</el-radio>
          <!-- <el-radio label="4">所有失败项</el-radio> -->
        </el-radio-group>
        <el-button style="margin-left: 20px" @click="readTabData"
          >读取数据</el-button
        >
        <el-button style="margin-left: 20px" @click="cancelData"
          >取消</el-button
        >
      </div>
      <div class="ll-control-item ll-item2">
        <div class="item1"></div>
        <div class="item2"></div>
        <div class="item3"></div>
      </div>
      <div class="ll-control-item"></div>
      <div class="ll-control-item"></div>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { lineLossData } from "@/gm/meterLabel.js";
import { meterMeterDataCollection } from "@/api/source.js";
import { useAppStore } from "@/stores";
import { storeToRefs } from "pinia";
const useApp = useAppStore();
let { monthMeterReading, currentPlanId } = storeToRefs(useApp);

const props = defineProps({
  currentData: Object,
});
const loadingRef = ref(false);
const tabPosition = ref("left");
const tableHeader = ref([]);
// console.log(lineLossData);
const tableData = ref();
const readRadio = ref("1");
const multipleSelection = ref([]);
const dataTabRef = ref();
const cellData = ref();
const tempData = ref();
const position = ref("");
const checkAll = ref([]);
const tabData = ref([]);
const percentage = ref(0);
const percentageFlag = ref(false);
const isContinue = ref(false);

const tableCellClassName = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex === 0) {
    return "first-column-class";
  }
  return "";
};
onMounted(() => {
  tableHeader.value = props.currentData.children.filter(
    (item) => item.type != 2 && item.type != 6
  );
  if (props.currentData.type === 8) {
    tableHeader.value = [props.currentData];
  }
  tableData.value = lineLossData.filter((item) => item.type != 3);
});
const handleSelectionChange = (data) => {
  multipleSelection.value = data;
};
const cancelData = () => {
  isContinue.value = true;
};
//table 头部点击
const headerClick = (val) => {
  if (val.property != "label" && val.property) {
    position.value = val.property;
    dataTabRef.value.setCurrentRow();
    var elements = document.getElementsByClassName(val.id);
    let obj = document.getElementsByClassName("el-table__cell");
    for (var i = 0; i < obj.length; i++) {
      // 设置背景色为红色
      obj[i].style.backgroundColor = "#fff";
    }
    // 遍历每个元素并设置样式属性值
    for (var i = 0; i < elements.length; i++) {
      // 设置背景色为红色
      elements[i].style.backgroundColor = "#e6f2f0";
    }
  }
};
//单元格点击
const cellClick = (row, event) => {
  if (event.property != "label") {
    let obj = {
      meterPositionId: event.property,
      row,
    };
    cellData.value = obj;
    multipleSelection.value = [];
    position.value = "";
    dataTabRef.value.clearSelection();
  }
};
//表格行点击事件
const rowClick = (row) => {
  position.value = "";
  cellData.value = "";
  let obj = document.getElementsByClassName("el-table__cell");
  for (var i = 0; i < obj.length; i++) {
    // 设置背景色为红色
    obj[i].style.backgroundColor = "#fff";
  }
};
// 抄表-读取表信息
const readTabData = () => {
  checkAll.value = [];
  percentage.value = 0;
  isContinue.value = false;
  if (readRadio.value === "3" || readRadio.value === "4") {
    let parm = [];
    tableHeader.value.forEach((item) => {
      tableData.value.forEach((item1) => {
        let obj = {
          pos: item.position,
          parm: [item1.parm1, item1.parm2],
          methodName: item1.parm0,
          planId: currentPlanId.value,
        };
        checkAll.value.push(item1.prop);
        parm.push(obj);
      });
    });
    meterMeterDataCollectionApi(parm, 0, 1);
  } else {
    if (
      multipleSelection.value.length > 0 ||
      position.value ||
      cellData.value
    ) {
      switch (readRadio.value) {
        case "1":
          //选中列
          if (position.value) {
            let parm = [];
            // 是否有多选
            if (multipleSelection.value.length > 0) {
              multipleSelection.value.forEach((item1) => {
                let obj = {
                  pos: position.value,
                  parm: [item1.parm1, item1.parm2],
                  methodName: item1.parm0,
                  planId: currentPlanId.value,
                };
                checkAll.value.push(item1.prop);
                parm.push(obj);
              });
            } else {
              tableData.value.forEach((item1) => {
                let obj = {
                  pos: position.value,
                  parm: [item1.parm1, item1.parm2],
                  methodName: item1.parm0,
                  planId: currentPlanId.value,
                };
                checkAll.value.push(item1.prop);
                parm.push(obj);
              });
            }
            meterMeterDataCollectionApi(parm, 0, 1); //接口调用
          }
          //选中行
          else if (multipleSelection.value.length > 0) {
            let tempArr = tableHeader.value;
            let parm = [];
            tempArr.forEach((item) => {
              multipleSelection.value.forEach((item1) => {
                let obj = {
                  pos: item.position,
                  parm: [item1.parm1, item1.parm2],
                  methodName: item1.parm0,
                  planId: currentPlanId.value,
                };
                checkAll.value.push(item1.prop);
                parm.push(obj);
              });
            });
            // console.log(parm);
            meterMeterDataCollectionApi(parm, 0, 1); //接口调用
          }
          //选中表格 cellData
          else if (cellData.value) {
            let parm = {
              pos: cellData.value.meterPositionId,
              parm: [cellData.value.row.parm1, cellData.value.row.parm2],
              methodName: cellData.value.row.parm0,
              planId: currentPlanId.value,
            };
            checkAll.value.push(cellData.value.row.prop);
            meterMeterDataCollectionApi([parm], 0, 1); //接口调用
          }
          break;
        case "2":
          if (!position.value) {
            ElMessage({
              message: "请先选择当前表信息",
              type: "warning",
            });
          } else {
            let parm = [];
            tableData.value.forEach((item1) => {
              let obj = {
                pos: position.value,
                parm: [item1.parm1, item1.parm2],
                methodName: item1.parm0,
                planId: currentPlanId.value,
              };
              checkAll.value.push(item1.prop);
              parm.push(obj);
            });
            meterMeterDataCollectionApi(parm, 0, 1);
          }
          break;
        case "4":
          break;
        default:
          break;
      }
    } else {
      ElMessage({
        message: "请先选择当前读取表信息",
        type: "warning",
      });
    }
  }
};
const meterMeterDataCollectionApi = async (params, i, type) => {
  loadingRef.value = true;
  percentageFlag.value = true;
  let parm = params[i];
  // console.log(parm);
  if (isContinue.value) {
    loadingRef.value = false;
  } else {
    await meterMeterDataCollection(parm)
      .then((res) => {
        if (type === 1) getParseData(parm, res.data.data, i); //匹配数据赋值
        if (++i < params.length) {
          meterMeterDataCollectionApi(params, i, type); //循环调用
        }
        getProcess(i);
      })
      .catch(() => {
        if (type === 1) getParseData(parm, "失败", i); //匹配数据赋值
        if (++i < params.length) {
          meterMeterDataCollectionApi(params, i, type); //循环调用
        }
        getProcess(i);
      });
    if (i == params.length) {
      loadingRef.value = false;
      let msg;
      if (type === 1) msg = "读取成功";
      if (type === 2) msg = "写入成功";
      else msg = "发送成功";
      ElMessage({
        type: "success",
        message: msg,
      });
    }
  }
};
const getParseData = (data, result, i) => {
  tableData.value.forEach((item) => {
    if (checkAll.value.includes(item.prop)) {
      //1.确定methodName
      if (item.parm0 === data.methodName) {
        //2.确定上月还是本月
        if (item.parm2 === data.parm[1]) {
          //3.确定尖峰平谷总
          if (item.parm1 === data.parm[0]) {
            item["value" + data.pos] = result;
          }
        }
      }
    }
  });
  //动态赋值
  if (readRadio.value === "1") {
    if (position.value) {
      monthMeterReading.value[position.value] = tableData.value; //抄表底数赋值
    } else if (multipleSelection.value.length > 0) {
      tableHeader.value.forEach((item1) => {
        monthMeterReading.value[item1.position] = tableData.value; //抄表底数赋值
      });
    } else {
      monthMeterReading.value[cellData.value.meterPositionId] = tableData.value; //抄表底数赋值
    }
  } else if (readRadio.value === "2") {
    tableHeader.value.forEach((item1) => {
      monthMeterReading.value[item1.position] = tableData.value; //抄表底数赋值
    });
  } else {
    tableHeader.value.forEach((item1) => {
      monthMeterReading.value[item1.position] = tableData.value; //抄表底数赋值
    });
  }
};
const getProcess = (i) => {
  let total;
  let percentage;
  if (readRadio.value === "3" || readRadio.value === "4") {
    total = tableHeader.value.length * tableData.value.length;
    percentage = Math.ceil((i / total) * 100).toFixed(2);
    changePercentageData(percentage);
  } else if (readRadio.value === "1") {
    if (position.value) {
      if (multipleSelection.value.length > 0) {
        percentage = "100";
        changePercentageData(percentage);
      } else {
        total = tableData.value.length;
        percentage = Math.ceil((i / total) * 100).toFixed(2);
        changePercentageData(percentage);
      }
    } else if (multipleSelection.value.length > 0) {
      total = tableHeader.value.length * multipleSelection.value.length;
      percentage = Math.ceil((i / total) * 100).toFixed(2);
      changePercentageData(percentage);
    } else if (cellData.value) {
      percentage = "100";
      changePercentageData(percentage);
    }
  } else if (readRadio.value === "2") {
    total = tableData.value.length;
    percentage = Math.ceil((i / total) * 100).toFixed(2);
    changePercentageData(percentage);
  }
};
const changePercentageData = (parm) => {
  percentage.value = Number(parm);
};
</script>

<style lang="scss" scoped>
//功率源
.meter-reading {
  width: 95%;
  .ll-control {
    margin-top: 5px;
    border: 1px solid #ebeef5;
    display: flex;
    justify-content: space-around;
    align-items: center;
    .ll-control-item {
      display: flex;
      align-items: center;
      .ll-group {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
      }
      .item2,
      .item3 {
        p {
          display: flex;
          padding: 5px 0px;
          .el-input {
            width: 100px;
          }
        }
      }
      .el-button {
        width: 100px;
      }
      .item2 {
        .el-button {
          width: 50px;
        }
      }
    }
    .ll-item2 {
      width: 700px;
      justify-content: space-evenly;
      align-items: center;
    }
  }
}
.first-column-class {
  background-color: #e6f2f0 !important;
}
</style>
